package com.example.thread.demo.util;

public class CalculateUtil {

    private final static int SIZE = 30;

    /**
     * 计算阶乘n!
     *
     * @param num
     * @return
     */
    public static int recursion(int num) {
        int sum = 1;
        if (0 > num) {
            throw new IllegalArgumentException("必须为正整数!");
        }
        if (1 == num) {
            return 1;
        } else {
            sum = sum * recursion(num - 1);
            return sum;
        }
    }

    /**
     * 计算2的N次方
     *
     * @param n
     * @return
     */
    public static String twoN(int n) {
        long beginTime = System.currentTimeMillis();
        int[] res = new int[SIZE + 1];
        int i;
        for (i = 0; i < SIZE; ++i) {
            res[i] = 0;
        }
        res[0] = 1;
        while (n > 0) {
            for (i = 0; i < SIZE; ++i) {
                res[i] *= 2;
            }
            for (i = 0; i < SIZE; ++i) {
                if (res[i] > 9) {
                    res[i + 1] += res[i] / 10;
                    res[i] %= 10;
                }
            }
            n--;
        }
        boolean b = false;
        StringBuffer sb = new StringBuffer();
        for (i = SIZE; i >= 0; --i) {
            if (res[i] != 0 || b) {
                sb.append(res[i]);
                b = true;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("第一种计算2的N次方耗时：" + (endTime - beginTime));
        return sb.toString();
    }

    /**
     * 计算2的n次方，根据高位低位
     *
     * @param N
     * @return
     */
    public static StringBuffer my_power_2(int N) {
        long beginTime = System.currentTimeMillis();
        StringBuffer v = new StringBuffer("");
        long num[] = new long[2];
        num[1] = 1;
        if (N > 62) {
            num[0] = 1;
            num[0] = num[0] << (N - 62);
            num[1] = num[1] << 62;
            String s = String.valueOf(num[1]);
            int size = 30, i = 0, j = 0;
            long n[] = new long[size + 1];
            //System.out.println(num[0]+" "+s);
            for (i = s.length() - 1; i >= 0; --i) {
                n[j++] = (long) (num[0] * (s.charAt(i) - '0'));
                //System.out.println(n[j - 1]);
            }
            for (i = 0; i < size; ++i) {
                while (n[i] > 9) {
                    n[i + 1] += n[i] / 10;
                    n[i] %= 10;
                }
            }
            boolean bl = false;
            for (i = size; i >= 0; --i) {
                if (n[i] != 0 || bl) {
                    v.append(n[i]);
                    bl = true;
                }
            }
        } else {
            num[1] = num[1] << N;
            v.append(String.valueOf(num[1]));
        }
        long endTime = System.currentTimeMillis();
        System.out.println("第二种计算2的N次方耗时：" + (endTime - beginTime));
        return v;
    }
}
